<template>
  <div class="four-level-cascader-demo">
    <!-- 应用头部 -->
    <header class="demo-header">
      <h1>🔗 四层级联选择器演示</h1>
      <p>Vue3 + TypeScript 支持四层深度的级联选择器完整实现</p>
    </header>

    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 级联选择器区域 -->
      <section class="cascader-section">
        <h2>📋 四层级联选择器</h2>
        
        <div class="cascader-container">
          <label class="cascader-label">选择组件分类（支持四层深度）:</label>
          <CascaderSelect
            v-model="selectedValue"
            :options="fourLevelOptions"
            placeholder="请选择组件分类..."
            @change="handleCascaderChange"
            :header-labels="headerLabels"
          />
        </div>

        <!-- 选中信息展示 -->
        <transition name="fade-slide">
          <div v-if="selectedValue.length > 0" class="selection-info">
            <h3>🎯 当前选中信息</h3>
            <div class="info-grid">
              <div class="info-item">
                <span class="label">完整路径:</span>
                <span class="value">{{ selectedLabels.join(' → ') }}</span>
              </div>
              <div class="info-item">
                <span class="label">选择层级:</span>
                <span class="value">第 {{ selectedValue.length }} 层 / 共 4 层</span>
              </div>
              <div class="info-item">
                <span class="label">请求参数:</span>
                <span class="value highlight">{{ requestParam }}</span>
              </div>
              <div class="info-item">
                <span class="label">层级说明:</span>
                <span class="value">{{ getLevelDescription() }}</span>
              </div>
            </div>

            <!-- 层级详情 -->
            <div class="level-details">
              <h4>📊 层级详情</h4>
              <div class="level-list">
                <div 
                  v-for="(value, index) in selectedValue" 
                  :key="index"
                  class="level-item"
                  :class="{ 'is-deepest': index === selectedValue.length - 1 }"
                >
                  <span class="level-number">L{{ index + 1 }}</span>
                  <span class="level-name">{{ headerLabels[index] }}:</span>
                  <span class="level-value">{{ selectedLabels[index] }}</span>
                  <code class="level-code">({{ value }})</code>
                </div>
              </div>
            </div>
          </div>
        </transition>
      </section>

      <!-- 模拟表格区域 -->
      <section class="table-section">
        <h2>📊 数据表格 (基于最深层级筛选)</h2>
        
        <!-- 请求信息 -->
        <div class="request-info">
          <h3>🔧 API 请求信息</h3>
          <div class="request-details">
            <div class="request-item">
              <span class="label">请求参数:</span>
              <code>{{ formatRequestParams() }}</code>
            </div>
            <div class="request-item">
              <span class="label">筛选逻辑:</span>
              <span>使用最深层级的 name 值 ({{ requestParam || 'null' }})</span>
            </div>
          </div>
        </div>

        <!-- 表格内容 -->
        <div class="table-container">
          <table class="demo-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>名称</th>
                <th>分类</th>
                <th>层级路径</th>
                <th>状态</th>
              </tr>
            </thead>
            <tbody>
              <tr v-if="loading">
                <td colspan="5" class="loading-cell">🔄 数据加载中...</td>
              </tr>
              <tr v-else-if="!tableData.length">
                <td colspan="5" class="empty-cell">📭 请选择筛选条件以加载数据</td>
              </tr>
              <tr v-else v-for="item in tableData" :key="item.id">
                <td>{{ item.id }}</td>
                <td>{{ item.name }}</td>
                <td>{{ item.category }}</td>
                <td class="path-cell">{{ item.path }}</td>
                <td>
                  <span :class="['status-badge', `status-${item.status}`]">
                    {{ item.statusText }}
                  </span>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </section>

      <!-- 操作日志 -->
      <section class="log-section">
        <h2>📝 操作日志</h2>
        <div class="log-container">
          <div v-for="(log, index) in operationLogs" :key="index" class="log-item">
            <span class="log-time">{{ log.time }}</span>
            <span class="log-message">{{ log.message }}</span>
          </div>
          <div v-if="!operationLogs.length" class="empty-log">
            暂无操作记录
          </div>
        </div>
      </section>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import CascaderSelect from './CascaderSelect.vue'
import type { CascaderOption } from './types/app'

// 修正后的四层数据结构
const fourLevelOptions: CascaderOption[] = [
  {
    name: 'component',
    nameCn: '组件',
    nameEn: 'Component',
    children: [
      {
        name: 'basic',
        nameCn: '基础组件',
        nameEn: 'Basic',
        children: [
          { 
            name: 'button', 
            nameCn: '按钮', 
            nameEn: 'Button',
            children: [
              { name: 'button11', nameCn: '按钮11', nameEn: 'Button11' },
              { name: 'input11', nameCn: '输入框11', nameEn: 'Input11' }
            ] 
          },
          { 
            name: 'input', 
            nameCn: '输入框', 
            nameEn: 'Input',
            children: [
              { name: 'button12', nameCn: '按钮12', nameEn: 'Button12' },
              { name: 'input112', nameCn: '输入框12', nameEn: 'Input12' }
            ]
          }
        ]
      },
      {
        name: 'basic2',
        nameCn: '基础组件2',
        nameEn: 'Basic2',
        children: [
          { 
            name: 'button2', 
            nameCn: '按钮2', 
            nameEn: 'Button2',
            children: [
              { name: 'button21', nameCn: '按钮21', nameEn: 'Button21' },
              { name: 'input22', nameCn: '输入框22', nameEn: 'Input22' }
            ] 
          },
          { 
            name: 'input2', 
            nameCn: '输入框2', 
            nameEn: 'Input2',
            children: [
              { name: 'button23', nameCn: '按钮23', nameEn: 'Button23' },
              { name: 'input24', nameCn: '输入框24', nameEn: 'Input24' }
            ]
          }
        ]
      },
      {
        name: 'basic3',
        nameCn: '基础组件3',
        nameEn: 'Basic3',
        children: [
          { 
            name: 'button3', 
            nameCn: '按钮3', 
            nameEn: 'Button3',
            children: [
              { name: 'button31', nameCn: '按钮31', nameEn: 'Button31' },
              { name: 'input32', nameCn: '输入框32', nameEn: 'Input32' }
            ]
          },
          { 
            name: 'input3', 
            nameCn: '输入框3', 
            nameEn: 'Input3',
            children: [
              { name: 'button33', nameCn: '按钮33', nameEn: 'Button33' },
              { name: 'input34', nameCn: '输入框34', nameEn: 'Input34' }
            ]
          }
        ]
      }
    ]
  }
]

// 四层级联选择器的头部标签
const headerLabels = ['根分类', '子分类', '组件类型', '具体组件']

// 响应式数据
const selectedValue = ref<string[]>([])
const selectedLabels = ref<string[]>([])
const tableData = ref<any[]>([])
const loading = ref(false)
const operationLogs = ref<Array<{time: string, message: string}>>([])

// 计算属性
const requestParam = computed(() => {
  if (!selectedValue.value.length) return ''
  return selectedValue.value[selectedValue.value.length - 1]
})

// 方法
const handleCascaderChange = (value: string[], selectedOptions: CascaderOption[]) => {
  selectedLabels.value = selectedOptions.map(opt => opt.nameCn)
  
  addLog(`级联选择器变更: ${selectedLabels.value.join(' → ')}`)
  addLog(`选择层级: 第 ${value.length} 层，提取请求参数: ${requestParam.value}`)
  
  if (requestParam.value) {
    loadTableData(requestParam.value)
  } else {
    tableData.value = []
  }
}

const getLevelDescription = (): string => {
  const level = selectedValue.value.length
  const descriptions = {
    1: '已选择根分类',
    2: '已选择到子分类',
    3: '已选择到组件类型',
    4: '已选择到具体组件（最深层级）'
  }
  return descriptions[level as keyof typeof descriptions] || '未知层级'
}

const formatRequestParams = () => {
  return JSON.stringify({
    category: requestParam.value || null,
    level: selectedValue.value.length,
    fullPath: selectedValue.value,
    page: 1,
    pageSize: 20
  }, null, 2)
}

const loadTableData = async (category: string) => {
  loading.value = true
  addLog(`开始请求表格数据: category=${category}`)
  
  try {
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 生成模拟数据
    const mockData = generateMockData(category)
    tableData.value = mockData
    
    addLog(`请求成功，获取到 ${mockData.length} 条数据`)
  } catch (error) {
    addLog(`请求失败: ${error}`)
  } finally {
    loading.value = false
  }
}

const generateMockData = (category: string) => {
  const pathMap: Record<string, string> = {
    'button11': '组件 → 基础组件 → 按钮 → 按钮11',
    'input11': '组件 → 基础组件 → 按钮 → 输入框11',
    'button12': '组件 → 基础组件 → 输入框 → 按钮12',
    'input112': '组件 → 基础组件 → 输入框 → 输入框12',
    'button21': '组件 → 基础组件2 → 按钮2 → 按钮21',
    'input22': '组件 → 基础组件2 → 按钮2 → 输入框22',
    'button23': '组件 → 基础组件2 → 输入框2 → 按钮23',
    'input24': '组件 → 基础组件2 → 输入框2 → 输入框24',
    'button31': '组件 → 基础组件3 → 按钮3 → 按钮31',
    'input32': '组件 → 基础组件3 → 按钮3 → 输入框32',
    'button33': '组件 → 基础组件3 → 输入框3 → 按钮33',
    'input34': '组件 → 基础组件3 → 输入框3 → 输入框34'
  }

  const baseData = [
    { id: 1, name: `${category} 组件实例`, category: category, status: 'active', statusText: '启用' },
    { id: 2, name: `${category} 高级版本`, category: category, status: 'active', statusText: '启用' },
    { id: 3, name: `${category} 测试版本`, category: category, status: 'pending', statusText: '开发中' }
  ]

  return baseData.map(item => ({
    ...item,
    path: pathMap[category] || '未知路径'
  }))
}

const addLog = (message: string) => {
  const now = new Date()
  const time = now.toLocaleTimeString()
  operationLogs.value.unshift({ time, message })
  
  if (operationLogs.value.length > 30) {
    operationLogs.value = operationLogs.value.slice(0, 30)
  }
}

// 监听选中值变化
watch(selectedValue, (newValue) => {
  console.log('四层级联选择器值变化:', newValue)
  console.log('当前选择层级:', newValue.length)
  console.log('最深层级参数:', requestParam.value)
})
</script>

<style scoped>
.four-level-cascader-demo {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 0;
}

.demo-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  text-align: center;
  padding: 32px 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.demo-header h1 {
  margin: 0 0 12px 0;
  font-size: 2.2rem;
  font-weight: 700;
}

.demo-header p {
  margin: 0;
  font-size: 1.1rem;
  opacity: 0.9;
}

.main-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 32px 20px;
}

.cascader-section,
.table-section,
.log-section {
  background: white;
  border-radius: 16px;
  padding: 32px;
  margin-bottom: 24px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  border: 1px solid #e9ecef;
}

.cascader-section h2,
.table-section h2,
.log-section h2 {
  margin: 0 0 24px 0;
  color: #2c3e50;
  font-size: 1.4rem;
  font-weight: 700;
  border-bottom: 2px solid #f1f3f5;
  padding-bottom: 12px;
}

.cascader-container {
  max-width: 600px;
  margin-bottom: 32px;
}

.cascader-label {
  display: block;
  margin-bottom: 12px;
  font-weight: 600;
  color: #374151;
  font-size: 1rem;
}

/* 选中信息样式 */
.selection-info {
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  border-radius: 12px;
  padding: 24px;
  border: 1px solid #cbd5e1;
}

.selection-info h3 {
  margin: 0 0 20px 0;
  color: #1e40af;
  font-size: 1.2rem;
  font-weight: 600;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-item .label {
  min-width: 80px;
  font-weight: 600;
  color: #6c757d;
}

.info-item .value {
  color: #495057;
  flex: 1;
}

.info-item .value.highlight {
  background: #e7f3ff;
  color: #667eea;
  padding: 4px 8px;
  border-radius: 4px;
  font-weight: 600;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
}

/* 层级详情样式 */
.level-details {
  padding-top: 20px;
  border-top: 1px solid #e2e8f0;
}

.level-details h4 {
  margin: 0 0 16px 0;
  color: #374151;
  font-size: 1.1rem;
}

.level-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.level-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 12px;
  background: white;
  border-radius: 6px;
  border: 1px solid #e5e7eb;
  transition: all 0.2s ease;
}

.level-item.is-deepest {
  background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
  border-color: #f59e0b;
}

.level-number {
  background: #3b82f6;
  color: white;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 0.8rem;
  font-weight: 600;
  min-width: 28px;
  text-align: center;
}

.is-deepest .level-number {
  background: #f59e0b;
}

.level-name {
  font-weight: 600;
  color: #4b5563;
  min-width: 80px;
}

.level-value {
  color: #1f2937;
  font-weight: 500;
}

.level-code {
  background: #f3f4f6;
  color: #6b7280;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 0.85rem;
}

/* 请求信息样式 */
.request-info {
  background: #f8fafc;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 24px;
  border: 1px solid #e2e8f0;
}

.request-info h3 {
  margin: 0 0 16px 0;
  color: #374151;
  font-size: 1.1rem;
}

.request-details {
  display: grid;
  gap: 12px;
}

.request-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.request-item .label {
  min-width: 90px;
  font-weight: 600;
  color: #6c757d;
}

.request-item code {
  background: #1e293b;
  color: #e2e8f0;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 0.85rem;
  white-space: pre-wrap;
  flex: 1;
}

/* 表格样式 */
.table-container {
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e5e7eb;
}

.demo-table {
  width: 100%;
  border-collapse: collapse;
  background: white;
}

.demo-table th {
  background: #f8fafc;
  padding: 16px 12px;
  text-align: left;
  font-weight: 600;
  color: #374151;
  border-bottom: 2px solid #e5e7eb;
}

.demo-table td {
  padding: 12px;
  border-bottom: 1px solid #f1f3f5;
}

.demo-table tr:hover {
  background-color: #f9fafb;
}

.path-cell {
  font-size: 0.9rem;
  color: #6b7280;
  max-width: 300px;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.8rem;
  font-weight: 500;
}

.status-active {
  background: #d1fae5;
  color: #065f46;
}

.status-pending {
  background: #fef3c7;
  color: #92400e;
}

.loading-cell, .empty-cell {
  text-align: center;
  color: #6c757d;
  font-style: italic;
  padding: 40px;
}

/* 日志样式 */
.log-container {
  max-height: 300px;
  overflow-y: auto;
  background: #f8fafc;
  border-radius: 8px;
  padding: 16px;
  border: 1px solid #e5e7eb;
}

.log-item {
  display: flex;
  gap: 12px;
  padding: 8px 0;
  border-bottom: 1px solid #e2e8f0;
  font-size: 0.9rem;
}

.log-time {
  color: #6b7280;
  font-weight: 500;
  min-width: 90px;
}

.log-message {
  color: #374151;
}

.empty-log {
  text-align: center;
  color: #9ca3af;
  font-style: italic;
  padding: 20px;
}

/* 过渡动画 */
.fade-slide-enter-active,
.fade-slide-leave-active {
  transition: all 0.3s ease;
}

.fade-slide-enter-from {
  opacity: 0;
  transform: translateY(-10px);
}

.fade-slide-leave-to {
  opacity: 0;
  transform: translateY(10px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-content {
    padding: 16px 10px;
  }
  
  .cascader-section,
  .table-section,
  .log-section {
    padding: 20px;
  }
  
  .demo-header h1 {
    font-size: 1.8rem;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .level-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 6px;
  }
  
  .request-item {
    flex-direction: column;
    gap: 6px;
  }
  
  .table-container {
    overflow-x: auto;
  }
}
</style>
